﻿using ScannerApp.Common;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Drawing;
using ScannerApp.Model;
using AutoUpdate.Log;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Net.Sockets;
using System.Net;
using static ScannerApp.Common.PopMessageHelper;
using System.Diagnostics;
using System.IO.Ports;
using System.Windows.Threading;
using ScannerApp.Business;

namespace ScannerApp
{
    /// <summary>
    /// VitalityAnalysis.xaml 的交互逻辑
    /// </summary>
    public partial class VitalityAnalysis : Window
    {
       
        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");
        string Com = "", BaudRate = "", DataBits = "", StopRate = "", ParityRate = "";
        SerialPort sp = new SerialPort();
        bool isCanSubmit = false;
        bool canscan = true;
        ViewModel vm;
        Dictionary<string, string> SendList = new Dictionary<string, string>();
        Dictionary<string, string> ReciveList = new Dictionary<string, string>();
        ScanApp.Boar_ISASpSUS bi = new ScanApp.Boar_ISASpSUS(); 
        private TcpClient tcpcz = null;
        private bool _isLoadSuccess = false;
        System.Windows.Threading.DispatcherTimer timer_heartbeat = new System.Windows.Threading.DispatcherTimer();


        [DllImport("user32.dll")]
        private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        const int SWP_SHOWWINDOW = 0x0040;

        public VitalityAnalysis()
        {
            InitializeComponent();
            //this.WindowState = System.Windows.WindowState.Maximized;
            czy.Text = publicclass.UserName;
            vm = (ViewModel)this.DataContext;
            vm.FocusLastItem += AutoScroll;
            vm.AddItemsToStatus("初始化...",0);
        }

        private void close_window(object sender, System.ComponentModel.CancelEventArgs e)
        {
            tips.SetResourceReference(TextBlock.TextProperty, "oClose");
            MessageBoxResult result = System.Windows.MessageBox.Show(tips.Text, "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            else {
                e.Cancel = true;
            }
        }

        private void close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            MessageBoxResult result = System.Windows.MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            else
            {

            }

        }

        private void tm1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            try
            {

                if (e.Key == Key.Enter)
                {
                    this._loading.Visibility = Visibility.Visible;
                    UIAction(() =>
                    {
                        LoadData(tm1.Text);
                        tm1.Text = "";
                    });
                    //button1.Focus();
                  
                    this._loading.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            }


        }
        
        
        private void read_Click(object sender, RoutedEventArgs e)
        {
            isCanSubmit = false; 
            Thread.Sleep(1000 * 2);
            try { 
            
            {
                if (!IsGet)
                {
                    Tips("ErrorVitGet"); return;
                }
                vm.listStatusClear();
                   
                    this._loading.Visibility = Visibility.Visible;
                    //  TTips("ErrorVitSaveing");
                    string addmsg = sa.Add_boar_ISASpSUS(bi);
                    string msg = sa.Update_boar_collection_status("VIT", zydh.Text.Trim());

                    if (zydh.Text.Trim() != "" && msg == "" && addmsg == "")
                {

                    string para = "{\"EventType\":\"种禽活力分析\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "\",\"Log_Content\":\"" + "【采集保存(状态)】 → 15\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                    string msglog = sa.Sys_log(para);
                   // Clear();
                    //保存
                        SendClient(ISASpSUSSendCommond.savedata + "\r\n");
                        Tips("SuccessVIT"); 
                        canscan = true;
                        tm1.IsEnabled = true;
                       // PopMessageHelper.ShowMessage("提交成功:" + msg + "！\r\n窗口3秒后关闭...", "成功提示", 3000, MsgStyle.OK);

                }
                else
                {
                        TipsSystem( msg + addmsg);
                }
                    //不管成功与否，清空
                    TTips("ErrorEmpty");
             this._loading.Visibility = Visibility.Collapsed;
            }
            IsGet = false;
            }
            catch (Exception ex)
            {
                this._loading.Visibility = Visibility.Collapsed;
                PopMessageHelper.ShowMessage("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "错误提示", 3000, MsgStyle.RedCritical_OK);
            }
           

        }
        bool IsGet = false;
        private void save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (zydh.Text.Trim() == "")
                {
                    Tips("ErrorVitNoData");
                    return;
                }
                this._loading.Visibility = Visibility.Visible;
                tm1.IsEnabled = true;
              // Tips("ErrorVitRecvie");
                ReciveData(1);
               // IsGet = true;
                //Tips("请确保ISAS软件已经捕获并分析！！");
                //ShowModalDialog(true);
                
                this._loading.Visibility = Visibility.Collapsed;
            }     
            catch (Exception ex)
            {
                this._loading.Visibility = Visibility.Collapsed;
                PopMessageHelper.ShowMessage("提示:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            }
            tm1.IsEnabled = false;

            }
        //选择订单
        private void btnSelect_Click(object sender, RoutedEventArgs e){
            SelectOrder so = new SelectOrder();
            so.GetIsStatus = "-20-_-40-_-50-";
            // 订阅事件
            so.PassValuesEvent += new SelectOrder.PassValuesHandler(ReceiveValues);

            so.Show();
        }
        //返回订单信息
        private void ReceiveValues(object sender, PassValuesEventArgs e)
        {
            string OrderID = e.OrderID;
            string ShortCode = e.ShortCode;
            object a = e.RowData;
            tm1.Text = OrderID;
            this._loading.Visibility = Visibility.Visible;
            UIAction(() =>
            {
                LoadData(OrderID);
                tm1.Text = "";
            });
            //button1.Focus();

            this._loading.Visibility = Visibility.Collapsed;
        }
        private void bh_Click(object sender, RoutedEventArgs e)
        {
            //捕获分析
            SendClient(ISASpSUSSendCommond.captureandanalize + "\r\n");
        }
        private void bh2_Click(object sender, RoutedEventArgs e)
        {
            //捕获分析
            SendClient(ISASpSUSSendCommond.capture + "\r\n");
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
               
                //Join WinAPI Setting Focse();
                IntPtr handle = new WindowInteropHelper(this).Handle;
                double y1 = SystemParameters.FullPrimaryScreenHeight;

                double x1 = SystemParameters.FullPrimaryScreenWidth;//得到屏幕整体高度
                SetWindowPos(handle, HWND_TOPMOST, 0, 0, (int)300, (int)1000, SWP_SHOWWINDOW);

                tm1.Focus();
                sysname.Text = publicclass.SystemName;
                save.IsEnabled = false;
                bh.IsEnabled = false;
                bh2.IsEnabled = false;
               // string preurl = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");

                // Uri uri = new Uri(preurl);
                // string imageurl = uri.Scheme + "://" + uri.Host + "/" + publicclass.SystemLogo;
                // Console.WriteLine(uri.Host);
                //  this.tb_1.Source = new BitmapImage(new Uri(imageurl));
                //初始化条码
                //tm();
                ////初始化发送/接收
                //InitIASApSUSData();
                //
                string[] s = System.IO.Ports.SerialPort.GetPortNames();
                if (ini.ExistINIFile())
                {
                    string Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                                                                  // string Com =  Common.ConfigHelper.GetIni("Com","");
                    if (s.Length < 1 || Com == "")
                    {
                        btndzc.Background = System.Windows.Media.Brushes.Red;
                        errorlink = 0;
                        ComSet wcs = new ComSet();
                        wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        wcs.updateMainwindowLabel += FuncSettingClosed;
                        wcs.ShowDialog();//模式，弹出！

                    }
                    else
                    {
                        UIAction(() =>
                        {
                            GetIni();
                        });
                    }

                }
                else
                {
                    btndzc.Background = System.Windows.Media.Brushes.Red;
                }
                InitTcpIP();
                //每秒看下，是否可以提交了
                timer_heartbeat.Interval = TimeSpan.FromMilliseconds(1000);
                timer_heartbeat.Tick += startAutoprint;
                timer_heartbeat.Start();
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                 
            }
        }
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        void LoadData(string tm)
        {
            try
            {
                if (!canscan) {//未提交前，不允许扫描
                    tm1.Text = "";
                    tm1.Focus();
                    return;
                }
                if (tm.Length <= 1)
                {
                    Tips("ErrorBarCode"); return;
                }
               int czzl= (int)float.Parse(cz.Text.Trim());
                if (czzl <1)
                {
                    Tips("ErrorVitMin");return;
                }


                DataTable lsdt = sa.GetDataTable_collection_condition(tm, "VIT");
                if (lsdt == null)
                {
                    Clear();
                    Tips("ErrorNoOrder");
                }
                else
                {
                    if (lsdt.Rows.Count <= 0)
                    {
                        Clear();
                        Tips("ErrorNoOrder");
                    }
                    else
                    {
                        SendClient(ISASpSUSSendCommond.savedata + "\r\n");
                        //新增
                        string msgs = ISASpSUSSendCommond.newanalysis;
                        string sendmsg = msgs + "\r\n";
                        SendClient(sendmsg);

                        foreach (DataRow dr in lsdt.Rows)
                        {
                            Tips("ErrorVitProcess");
                            zydh.Text = dr["id"].ToString();
                            ddbh.Text = dr["pz"].ToString();
                            cpsl.Text = dr["nlday"].ToString();
                            mfrl.Text = dr["capacity"].ToString();
                            ddjq.Text = dr["collectDate"].ToString();
                            sccj.Text = dr["collector"].ToString();
                            usemml.Text = dr["usemml"].ToString();

                            bi.collectionID = dr["id"].ToString();
                            //一次剂量
                            int dosisvolume = (int)float.Parse(dr["capacity"].ToString());
                            bi.dosisvolume = dosisvolume;
                            SendClient(ISASpSUSSendCommond.putdata_dosisvolume + " " + dosisvolume.ToString() + "\r\n");
                            //collector
                            bi.collector = dr["uid"].ToString();
                            SendClient(ISASpSUSSendCommond.putdata_collector + " " + dr["uid"].ToString() + "\r\n");
                            //operator
                            bi.c_operator = publicclass.UserID;
                            SendClient(ISASpSUSSendCommond.putdata_operator + " " + publicclass.UserID + "\r\n");
                            //称重量
                            int ej = (int)float.Parse(cz.Text.Trim());
                                //(int)float.Parse(dr["weights"].ToString());
                            bi.ejaculatedvolume = ej;
                            SendClient(ISASpSUSSendCommond.putdata_ejaculatedvolume + " " + ej.ToString() + "\r\n");
                            //种禽名称
                            bi.c_subject = dr["barcode"].ToString();
                            SendClient(ISASpSUSSendCommond.putdata_subject + " " + dr["barcode"].ToString() + "\r\n");
                            Thread.Sleep(1000 * 8);
                            //捕获分析
                            //SendClient(ISASpSUSSendCommond.captureandanalize+"\r\n");
                            save.IsEnabled = true;
                            bh.IsEnabled = true;
                            bh2.IsEnabled = true;
                       
                        }
                        UIAction(() =>
                        {
                            tm1.IsEnabled = false;
                            canscan = false;
                            Tips("ErrorVitSave");
                            this._loading.Visibility = Visibility.Visible;
                            //Thread.Sleep(5000 * 8);
                            //save_Click(null, null);

                            this._loading.Visibility = Visibility.Collapsed;
                        });
                        //获取

                    }

                }
            }
            catch (Exception ex)
            {
                ScannerApp.Common.AutoClosedMsgBox.Show("提示:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.BlueInfo_OK);

            }

        }
        private void startAutoprint(object sender, EventArgs e)
        {
            if (isCanSubmit)
                read_Click(null,null);

        }


        void Clear()
        {
            vm.listStatusClear();

                    zydh.Text = "";
                    ddbh.Text = "";
                    cpsl.Text = "";
                    mfrl.Text = "";
                    ddjq.Text = "";
                //yysj.Text = "";
                    usemml.Text = "";
                    sccj.Text = "";
        }

        void tm()
        {
            System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

           // DisplayImg(image, cztm); 

        }

        void DisplayImg(System.Drawing.Image image, System.Windows.Controls.Image cimage)
        {
            //System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
                                                                   // 下行,初始一个 ImageSource 作为 myImage 的Source
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bi.EndInit();
            cimage.Source = bi; // done!
            ms.Close();
        }
        //从服务器获取全部有效数据
        int recvice = 0;
         
        void ReciveData(int rsend)
        {
            //SendClient(ISASpSUSSendCommond.savedata + "\r\n");
            save.IsEnabled = false;
            bh.IsEnabled = false;
            bh2.IsEnabled = false;
            recvice = rsend;
                switch (rsend)
                {
                    case 1:
                        SendClient(ISASpSUSReciveCommond.getdata_casereference + "\r\n");
                        break;
                  case 2:
                        SendClient(ISASpSUSReciveCommond.getdata_produceddosis + "\r\n");
                        break;
                    case 3:
                        SendClient(ISASpSUSReciveCommond.getdata_diluentvolume + "\r\n");
                        break;
                    case 4:
                        SendClient(ISASpSUSReciveCommond.getdata_totalfinalvolume + "\r\n");

                    //获取全部完成,kaishi
            
                    //提交
                   // read_Click(null, null);
                    break;
                case 5:
                    SendClient(ISASpSUSReciveCommond.getdata_totalspermsperdosis + "\r\n");
                    break;

                case 6:
                    SendClient(ISASpSUSReciveCommond.getdata_dilutionratio + "\r\n");
                    break;
                case 7:
                    SendClient(ISASpSUSReciveCommond.getdata_usemml + "\r\n");
                    break;
                //新加字段totnumber
                case 8:
                    SendClient(ISASpSUSReciveCommond.getfielddata_totnumber + "\r\n");
                    break;
                //新加字段totpercen
                case 9:
                    SendClient(ISASpSUSReciveCommond.getfielddata_totpercen + "\r\n");
                    break;
                case 10:
                    SendClient(ISASpSUSReciveCommond.getfielddata_totmml + "\r\n");
                    break;
                case 11:
                    SendClient(ISASpSUSReciveCommond.getfielddata_nornumber + "\r\n");
                    break;
                case 12:
                    SendClient(ISASpSUSReciveCommond.getfielddata_norpercen + "\r\n");
                    break;
                case 13:
                    SendClient(ISASpSUSReciveCommond.getfielddata_normillions + "\r\n");
                    break;
                case 14:
                    SendClient(ISASpSUSReciveCommond.getfielddata_normml + "\r\n");
                    break;
                case 15:
                    SendClient(ISASpSUSReciveCommond.getfielddata_motnumber + "\r\n");
                    break;
                case 16:
                    SendClient(ISASpSUSReciveCommond.getfielddata_motpercen + "\r\n");
                    break;
                case 17:
                    SendClient(ISASpSUSReciveCommond.getfielddata_motmillions + "\r\n");
                    break;
                case 18:
                    SendClient(ISASpSUSReciveCommond.getfielddata_motmml + "\r\n");
                    break;
                case 19:
                    SendClient(ISASpSUSReciveCommond.getfielddata_mnonumber + "\r\n");
                    break;
                case 20:
                    SendClient(ISASpSUSReciveCommond.getfielddata_mnopercen + "\r\n");
                    break;
                case 21:
                    SendClient(ISASpSUSReciveCommond.getfielddata_mnomillions + "\r\n");
                    break;
                case 22:
                    SendClient(ISASpSUSReciveCommond.getfielddata_mnomml + "\r\n");
                    break;
                case 23:
                    SendClient(ISASpSUSReciveCommond.getfielddata_usenumber + "\r\n");
                    break;
                case 24:
                    SendClient(ISASpSUSReciveCommond.getfielddata_usenumber + "\r\n");
                    break;
                case 25:
                    SendClient(ISASpSUSReciveCommond.getfielddata_usemillions + "\r\n");
                    break;
                case 26:
                    SendClient(ISASpSUSReciveCommond.getdata_totmillions + "\r\n");
                    break;
            }
        }

        void InitIASApSUSData()
        {
            //SendList.Add(XHDre, "");
            SendList.Add("putdata_collector", "");
            SendList.Add("putdata_operator", publicclass.UserID);
            SendList.Add("putdata_dosisvolume", "");
            SendList.Add("putdata_subject", "");
            SendList.Add("putdata_ejaculatedvolume", "");

            ReciveList.Add("getdata_casereference", "");
            ReciveList.Add("getdata_produceddosis", "");
            ReciveList.Add("getdata_diluentvolume", "");
            ReciveList.Add("getdata_totalfinalvolume", "");

        }

        void Tips(string msg)
        {
            UIAction(() =>
            {
                tipslan.SetResourceReference(TextBlock.TextProperty, msg);
                vm.AddItemsToStatus( tipslan.Text, 2);
                ScannerApp.Common.AutoClosedMsgBox.Show( tipslan.Text  , "Tips", 3000, MsgBoxStyle.BlueInfo_OK);

            });
           Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + msg, LogType.Error, "VIT");
            tm1.Focus(); return;
        }
        void TipsSystem(string msg)
        {
            UIAction(() =>
            {
               
                vm.AddItemsToStatus("错误:" + msg, 2);
                ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + msg, "提示", 3000, MsgBoxStyle.BlueInfo_OK);

            });
            Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + msg, LogType.Error, "VIT");
            tm1.Focus(); return;
        }

        void UILoad(TextBlock t,string st)
        {
            UIAction(() =>
            {
                t.Text = st;
            });
        }

        void TTips(string msg)
        {
            UIAction(() =>
            {
                ttips.SetResourceReference(TextBlock.TextProperty, msg);

               // ttips.Text = msg;
            });
        }

        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }
        /// <summary>
        /// 滚动条自动滚动
        /// </summary>
        private void AutoScroll()
        {
            StatusList.ScrollIntoView(StatusList.Items[StatusList.Items.Count - 1]);
        }

        private void InitTcpIP()
        {
            if(!IsConnected)
            {
                string ip = "127.0.0.1";//"127.0.0.1";"192.168.1.109"
                int port = 3000;
                Connect(ip,port);
            }

            //tcpip_client.RemoteIp = "127.0.0.1";
            //tcpip_client.RemotePort = 3000;
            //if (!tcpip_client.IsConnected)
            //{
            //    tcpip_client.ConnectToServer();
            //}

            if (!IsConnected)
            {
               // read.Content = "连接TCP";
                UIAction(() =>
                {
                    red.FontSize = 15;
                    red.Text = "连接失败！请先打开ISASpSUS！";
                });
                vm.AddItemsToStatus("连接失败！请先打开ISASpSUS！", 2);
            }  else
            {
               // read.Content = "提交";
                UIAction(() =>
                {
                    green.Text = "连接成功！";
                   
                });
                vm.AddItemsToStatus("连接成功！", 0);
            }


        }


        public void ShowData(string msg)
        {
            vm.AddItemsToStatus( "接收:"+ msg, 0);
        }


        #region TCPIP
        public bool IsConnected = false;
        Socket socketClient = null;
        Thread threadClient = null;
        public void Connect(string ipaddress, int portNum)
        {
            IPAddress address = IPAddress.Parse(ipaddress);
            IPEndPoint endPoint = new IPEndPoint(address, portNum);
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                vm.AddItemsToStatus("与服务器连接中" , 0); 
                socketClient.Connect(endPoint);

            }
            catch (SocketException se)
            {
                vm.AddItemsToStatus("连接失败！"+ se.Message, 2);
                IsConnected = false;
                return;
            }
            vm.AddItemsToStatus("连接成功！", 0);
            IsConnected = true;
            threadClient = new Thread(RecMsg);
            threadClient.IsBackground = true;
            threadClient.Start(socketClient);
        }

        //处理tcp接收的数据。
        void RecMsg(object sockConnectionparn)
        {
            Socket sockConnection = sockConnectionparn as Socket;
            EndPoint remoteEndPoint = new IPEndPoint(0, 0); ;
            byte[] buffMsgRec = new byte[1024];//* 1024 * 10

            int length = -1;

            while (true)
            {

                try
                {


                    length = sockConnection.Receive(buffMsgRec);
                    string receiveText = System.Text.Encoding.Default.GetString(buffMsgRec, 0, length);// 将接受到的字节数据转化成字符串；  
                    UIAction(() =>
                    {
                        vm.AddItemsToStatus(receiveText, 0);
                        if (receiveText == "ok\r\n")
                        {
                            //receiveText = receiveText + DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss");
                        }
                        else
                        {
                            //int rrecive = 1;
                            receiveText = receiveText.Replace("\r\n","");
                            Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + recvice+"=>"+ receiveText+"==>"+ bi, LogType.Error, "VIT");

                            switch (recvice)
                            {
                                case 1:
                                    bi.casereference = receiveText;
                                   // UILoad(t0,receiveText);
                                    ReciveData(2);
                                    break;
                                case 2:
                                    bi.produceddosis = int.Parse(receiveText);
                                  //  UILoad(t1, receiveText);
                                    ReciveData(3);
                                    break;
                                case 3:
                                    bi.diluentvolume = int.Parse(receiveText);
                                  //  UILoad(t2, receiveText);
                                    ReciveData(4);
                                    break;
                                case 4:
                                    bi.totalfinalvolume = int.Parse(receiveText);
                                   // UILoad(t3, receiveText);
                                    ReciveData(5); 
                                    break;
                                case 5:
                                    bi.Totalspermsperdosis = int.Parse(receiveText);
                                   // UILoad(t4, receiveText);
                                    ReciveData(6); 
                                    break;
                                case 6:
                                    bi.Dilutionratio = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(7); 
                                    break;
                                case 7:
                                   // Logger.Instance.WriteLog(publicclass.UserName + "[USEMML]" + receiveText, LogType.Error, "VIT");

                                    bi.Usemml = decimal.Parse(receiveText);
                                    //Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + receiveText, LogType.Error, "VIT");

                                    // UILoad(t5, receiveText);
                                    ReciveData(8);
                                    break;
                                case 8:
                                      bi.Totnumber = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(9);
                                    break;
                                case 9:
                                    bi.Totpercen = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                     ReciveData(10);
                                    //Logger.Instance.WriteLog(publicclass.UserName + "[分析]" + Vitbi, LogType.Error, "VIT");
 
                                    break;
                                case 10:
                                    bi.Totmml = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(11);
                                    break;
                                case 11:
                                    bi.Nornumber = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(12);
                                    break;
                                case 12:
                                    bi.Norpercen = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(13);
                                    break;
                                case 13:
                                    bi.Normillions = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(14);
                                    break;
                                case 14:
                                    bi.Normml = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(15);
                                    break;
                                case 15:
                                    bi.Motnumber = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(16);
                                    break;
                                case 16:
                                    bi.Motpercen = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(17);
                                    break;
                                case 17:
                                    bi.Motmillions = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(18);
                                    break;
                                case 18:
                                    bi.Motmml = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(19);
                                    break;
                                case 19:
                                    bi.Mnonumber = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(20);
                                    break;
                                case 20:
                                    bi.Mnopercen = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(21);
                                    break;
                                case 21:
                                    bi.Mnomillions = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(22);
                                    break;
                                case 22:
                                    bi.Mnomml = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(23);
                                    break;
                                case 23:
                                    bi.Usenumber = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(24);
                                    break;
                                case 24:
                                    bi.Usepercen = decimal.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    ReciveData(25);
                                    break;
                                case 25:
                                    bi.Usemillions = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    // ReciveData(23);
                                    ReciveData(26);
                                    break;
                                case 26:
                                    bi.Totmillions = int.Parse(receiveText);
                                    // UILoad(t5, receiveText);
                                    // ReciveData(23);
                                    StopReciveData();
                                    break;
                            }

                        }
                    });
                    //

                }

                catch (SocketException se)
                {
                    vm.AddItemsToStatus(se.Message, 2);
                    return;

                }
                catch (ThreadAbortException te)
                {
                    vm.AddItemsToStatus(te.Message, 2);
                    return;

                }
                catch (Exception e)
                {
                    vm.AddItemsToStatus(e.Message, 2);
                    return;

                }



                Thread.Sleep(10);


            }


        }
        //完成接收数据 最后一个ReciveData
        void StopReciveData()
        {
            recvice = 0;
            isCanSubmit = true; //全部获取完成，可以提交了
            IsGet = true;
        }
        //断开连接
        public void UnConnect()
        {
            try
            {
                threadClient.Abort();
                socketClient.Close();
            }
            catch(Exception e)
            {
                vm.AddItemsToStatus(e.Message, 2);
                return;
            }
            vm.AddItemsToStatus("已经断开连接！", 2);
            IsConnected = false;
        }



        //发送数据
        public void SendClient(string Msg)
        {
              SendMsg(socketClient, Msg);
            Thread.Sleep(100);
        }
        //发送数据
        private void SendMsg(object sockConnectionparn, string SendMsg)
        {
            Socket sockConnection = sockConnectionparn as Socket;

            if (!sockConnection.IsBound)
            {
                vm.AddItemsToStatus("请先建立连接！", 2);
                return;
            }
            try
            {
                string sendData = SendMsg;    //复制发送数据

                //字符串发送

                //serial.Write(sendData);
                byte[] arrData = System.Text.Encoding.Default.GetBytes(sendData);
                int i = sockConnection.Send(arrData);

                if (i > 0)
                    return;
                else {
                    vm.AddItemsToStatus("发送0个字节！", 2);
                    return;
                };

            }
            catch (Exception ex)
            {
                vm.AddItemsToStatus(ex.Message, 2);
                return ;
            }

        }
        #endregion

        private void Button_Click(object sender, RoutedEventArgs e)
        {
             
            ComSet wcs = new ComSet();
            wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            wcs.updateMainwindowLabel += FuncSettingClosed;
            wcs.ShowDialog();//模式，弹出！
        }

        //返回时候触发这个函数
        private void FuncSettingClosed(string labelContent)
        {

            string Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                                                          //    string Com = Common.ConfigHelper.GetIni("Com", "");
            if (Com == "" && labelContent == "0")
            {
                PopMessageHelper.ShowMessage("检测没有初始化串口，无法采集信息，请重新设置！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                ComSet wcs = new ComSet();
                wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                wcs.updateMainwindowLabel += FuncSettingClosed;
                wcs.ShowDialog();//模式，弹出！ 

            }
            else
            {
                UIAction(() =>
                {
                    GetIni();
                });
               
            }
            //label.Content = labelContent;

        }
        private void GetIni()
        {
            if (ini.ExistINIFile())
            {
                Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                BaudRate = ini.IniReadValue("串口设置", "BaudRate"); //Common.ConfigHelper.GetIni("BaudRate", "");
                DataBits = ini.IniReadValue("串口设置", "DataBits");//Common.ConfigHelper.GetIni("DataBits", "");
                StopRate = ini.IniReadValue("串口设置", "StopRate");//Common.ConfigHelper.GetIni("StopRate", "");
                ParityRate = ini.IniReadValue("串口设置", "ParityRate"); //Common.ConfigHelper.GetIni("ParityRate", "");
            }
            LinkSeriPort();
        }
        private int errorlink = 0;
        void LinkSeriPort()
        {

            try
            {

                //串口设置默认选择项  
                //cbSerial = 0;         
                string PortName = Com;//串口名    默认值第一个
                int BR = int.Parse(BaudRate);//获取或设置串行 波特率bit/s  默认值9600
                int DB = int.Parse(DataBits); ;//获取或设置每个字节的标准数据位长度 默认值8
                StopBits Stop = (StopBits)Convert.ToDouble(StopRate); ;//获取或设置每个字节的标准停止位数    默认值One 

                Parity ParityBits = Parity.None;//获取或设置奇偶校验检查协议    默认值None
                ParityBits = ParityRate == "None" ? Parity.None : Parity.Odd;//目前就2个

                if (sp.IsOpen)//先判断是否打开 
                    sp.Close();
                sp = new SerialPort(PortName, BR, ParityBits, DB, Stop);
                sp.WriteTimeout = 3000;
                sp.ReadTimeout = 3000;
                sp.Open();
                if (!sp.IsOpen)//再判断是否打开成功
                {
                    errorlink++;

                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(10);
                    timer.Tick += (x, y) =>
                    { 
                        LinkSeriPort();
                    };
                    timer.Start();
                    return;
                }
                else
                {
                    btndzc.Background = System.Windows.Media.Brushes.Green;

                    errorlink = 0; 

                    //UIAction(() =>
                    //{
                    sp.ReceivedBytesThreshold = 1;//接收缓冲区当中如果有一个字节的话就出发接收函数

                    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //订阅委托
                                                                                            //});





                }
            }
            catch (Exception ex)
            {
                 

                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }
        private void sp_DataReceived_old(object sender, SerialDataReceivedEventArgs e)

        {
            try
            {
                Thread.Sleep(100);//发送和接收均为文本时，接收中为加入判断是否为文字的算法，发送你（C4E3），接收可能识别为C4,E3，可用在这里加延时解决

                if (sp.IsOpen)     //此处可能没有必要判断是否打开串口，但为了严谨性，我还是加上了

                {
                    int count = sp.BytesToRead;
                    if (count <= 0 || count <= 6)//发现后面g /r/n会第二次分发
                        return;
                    //Thread.Sleep(10);
                    try
                    {
                        byte[] RS232DataBuff = new byte[count];    //BytesToRead:sp1接收的字符个数 

                        try

                        {

                            Byte[] receivedData = new Byte[sp.BytesToRead];        //创建接收字节数组

                            sp.Read(receivedData, 0, receivedData.Length);         //读取数据                       

                            sp.DiscardInBuffer();
                            //清空SerialPort控件的Buffer

                            string g_s_Data = "K +   189.2  g";
                            //Byte[] RData = new Byte[16];
                            //}
                            if (receivedData.Length < 15) return;
                            //if (receivedData[0].ToString("X2") != "4B") return;
                            //if (receivedData[receivedData.Length - 1].ToString("X2") != "0D"
                            //    || receivedData[receivedData.Length].ToString("X2") != "0A")
                            //{
                            //    return;
                            //}

                            string strRcv = System.Text.Encoding.Default.GetString(receivedData);
                            // Logger.Instance.WriteLog(strRcv, LogType.Information, "weight");

                            //  Logger.Instance.WriteLog( "[处理前]"+ g_s_Data, LogType.Information, "xsweight");
                            bool sffs = false;
                            if (strRcv.Contains("-")) sffs = true;
                            string strzl = strRcv.Replace("g", "").Replace(" ", "").Replace("\r\n", "")
                                 .Replace("K", "").Replace("*", "").Replace("+", "").Replace("-", "")
                                 .Replace("\n", "").Replace("\r", "");
                            // Logger.Instance.WriteLog("处理后："+strzl, LogType.Information, "xsweight");
                            if (StrCount(strzl, ".") > 1) return;
                            float a = 0;
                            try { a = float.Parse(strzl); } catch { }
                            if (strzl != "")
                                if (strzl != "")
                                    UIAction(() =>
                                    {
                                        cz.Text = a.ToString();// float.Parse(strzl).ToString();
                                    });
                         
                        }
                        catch (System.Exception ex)
                        {
                            ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                            return;


                        }
                    }
                    catch (Exception ex)
                    {
                        ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                        Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                        return;

                    }

                }

                else
                {
                    //zt.Text = "串口打开失败！重试:" + errorlink;
                    //zt.Foreground = Brushes.Red;
                    LinkSeriPort();

                }
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }
        private int StrCount(string str, string constr)
        {
            int c = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i].ToString() == constr)
                {
                    c++;
                }
            }
            return c;
        }
        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)

        {
            try
            {
                Thread.Sleep(10);//发送和接收均为文本时，接收中为加入判断是否为文字的算法，发送你（C4E3），接收可能识别为C4,E3，可用在这里加延时解决

                if (sp.IsOpen)     //此处可能没有必要判断是否打开串口，但为了严谨性，我还是加上了

                {
                    int count = sp.BytesToRead;
                    if (count <= 0 || count <= 6)//发现后面g /r/n会第二次分发
                        return;
                    //Thread.Sleep(10);
                    try
                    {
                        byte[] RS232DataBuff = new byte[count];    //BytesToRead:sp1接收的字符个数 

                        try

                        {

                            Byte[] receivedData = new Byte[sp.BytesToRead];        //创建接收字节数组

                            sp.Read(receivedData, 0, receivedData.Length);         //读取数据                       

                            sp.DiscardInBuffer();                                  //清空SerialPort控件的Buffer
                            string strRcv = "";
                            string g_s_Data = "";
                         
                            UIAction(() =>
                            {
                                cz.Text = "0";
                            });

                            for (int i = 0; i < receivedData.Length; i++) //窗体显示
                            {
                                //if (Convert.ToChar(receivedData[0]).ToString() == "-")
                                //{
                                //    cz.Text = "-";
                                //}
                                //if (i > 0)
                                g_s_Data += Convert.ToChar(receivedData[i]);
                                strRcv += Convert.ToChar(receivedData[i]);
                                //strRcv += receivedData[i].ToString("X2");  //16进制显示 
                            }
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]", LogType.Information, "weight");

                            string strzl = g_s_Data.Replace("g", "").Replace(" ", "").Replace("\r\n", "").Replace("+", "").Replace("\n", "").Replace("\r", "");
                            //cz.Dispatcher.BeginInvoke(new Action(() =>
                            //{
                            //    cz.Text = float.Parse(zl).ToString();
                            //}));
                            float a =0;
                            try { a = float.Parse(strzl); } catch { }
                            if (strzl != "")
                                UIAction(() =>
                                {
                                    cz.Text = a.ToString();// float.Parse(strzl).ToString();
                                });
                            //SetText(zl);
                            //这里需要解析字符串
                            //正负 空格 数字（10000）.数字（1）单位（2）
                            // cz.Text = "A:"+ g_s_Data+"|B:"+strRcv;
                            // txtReceive.Text += strRcv + "\r\n";

                        }
                        catch (System.Exception ex)
                        {
                            ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                            return;
                         

                        }
                    }
                    catch (Exception ex)
                    {
                        ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                        Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                        return;
                     
                    }

                }

                else
                {
                    //zt.Text = "串口打开失败！重试:" + errorlink;
                    //zt.Foreground = Brushes.Red;
                    LinkSeriPort();

                }
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }



        private void ShowModalDialog(bool bShow)
        {
            this.ModalDialog.IsOpen = bShow;
            // this.MainPanel.IsEnabled = !bShow;
        }

        private void Dlg_BtnClose_Click(object sender, RoutedEventArgs e)
        {
            ShowModalDialog(false);

        }

    }

}
